package cn.yinyu.queue.module.ecg.dal.mysql.queue;

import cn.yinyu.queue.framework.common.pojo.PageResult;
import cn.yinyu.queue.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.yinyu.queue.framework.mybatis.core.mapper.BaseMapperX;
import cn.yinyu.queue.module.ecg.dal.dataobject.queue.QueueDO;
import cn.yinyu.queue.module.ecg.dal.dataobject.queue.BedQueueStatisticDO;
import cn.yinyu.queue.module.ecg.dal.dataobject.queue.QueueStatisticDO;
import org.apache.ibatis.annotations.*;
import cn.yinyu.queue.module.ecg.controller.admin.queue.vo.*;

import java.util.List;

/**
 * 排队 Mapper
 *
 * @author 垠域源码
 */
@Mapper
public interface QueueMapper extends BaseMapperX<QueueDO> {

    default PageResult<QueueDO> selectPage(QueuePageReqVO reqVO) {
        return selectPage(reqVO, new LambdaQueryWrapperX<QueueDO>()
                .eqIfPresent(QueueDO::getPatId, reqVO.getPatId())
                .likeIfPresent(QueueDO::getPatName, reqVO.getPatName())
                .eqIfPresent(QueueDO::getPatGender, reqVO.getPatGender())
                .eqIfPresent(QueueDO::getBookTimeslot, reqVO.getBookTimeslot())
                .eqIfPresent(QueueDO::getBookCheckType, reqVO.getBookCheckType())
                .eqIfPresent(QueueDO::getSeqNum, reqVO.getSeqNum())
                .inIfPresent(QueueDO::getStatus, reqVO.getStatus())
                .eqIfPresent(QueueDO::getPassed, reqVO.getPassed())
                .eqIfPresent(QueueDO::getExpired, reqVO.getExpired())
                .eqIfPresent(QueueDO::getRoomId, reqVO.getRoomId())
                .eqIfPresent(QueueDO::getBedNo, reqVO.getBedNo())
                .betweenIfPresent(QueueDO::getCreateTime, reqVO.getCreateTime())
                .orderByDesc(QueueDO::getId));
    }

    @Select("SELECT max(seq_num) FROM yy_queue.queue")
    Integer getMaxSeqNum();

    @Select("SELECT * FROM yy_queue.queue where seq_num = #{seqNum}")
    QueueDO getQueueItemBySeqNum(@Param("seqNum")Integer seqNum);

    @Select("SELECT * FROM yy_queue.queue where pat_id = #{patId}")
    QueueDO getQueueByPatId(@Param("patId")String patId);

    @Select("<script>" +
            "SELECT * FROM yy_queue.queue " +
            "where room_id = #{roomId} and status in (" +
            " <foreach collection='statusList' separator=',' item='status'>" +
            " #{status} " +
            " </foreach> )" +
            " order by status desc, seq_num" +
            "</script>")
    List<QueueDO> getRoomQueueByStatus(@Param("roomId")Long roomId, @Param("statusList")List<Integer> statusList);

    @Select("<script>" +
            "SELECT * FROM yy_queue.queue " +
            "where status in (" +
            " <foreach collection='statusList' separator=',' item='status'>" +
            "  #{status} " +
            " </foreach> )" +
            " order by status desc, seq_num" +
            "</script>")
    List<QueueDO> getQueueByStatus( @Param("statusList")List<Integer> statusList);

    @Select("<script>" +
            "SELECT * FROM yy_queue.queue " +
            "where pat_id = #{patId} " +
            "  and book_check_type in (" +
            "    <foreach collection='arrCheckType' separator=',' item='checkType'>" +
            "      #{checkType} " +
            "    </foreach> )" +
            "  and TO_DAYS(book_date) = TO_DAYS(NOW()) " +
            "</script>")
    List<QueueDO> getCurPatGivenCheckTypes(@Param("patId")String patId, @Param("arrCheckType")Integer[] arrCheckType);

    @Select("<script>" +
            "SELECT * FROM yy_queue.queue " +
            "where pat_id = #{patId} " +
            "  and book_check_type in (" +
            "    <foreach collection='arrCheckType' separator=',' item='_checkType'>" +
            "      #{_checkType} " +
            "    </foreach> ) " +
            "  and status = #{status} " +
            "  and TO_DAYS(book_date) = TO_DAYS(NOW()) " +
            "</script>")
    List<QueueDO> getCurPatGivenCheckTypesAndStatus(@Param("patId")String patId, @Param("arrCheckType")Integer[] arrCheckType, @Param("status")Integer status);

    @Select("<script>" +
            "SELECT * FROM yy_queue.queue " +
            "where pat_id = #{patId} " +
            "  and book_check_type in (" +
            "    <foreach collection='arrCheckType' separator=',' item='_checkType'>" +
            "      #{_checkType} " +
            "    </foreach> ) " +
            "  and status in (" +
            "    <foreach collection='statusList' separator=',' item='_status'>" +
            "      #{_status} " +
            "    </foreach> ) " +
            "  and TO_DAYS(book_date) = TO_DAYS(NOW()) " +
            "</script>")
    List<QueueDO> getCurPatGivenCheckTypesAndStatusList(@Param("patId")String patId, @Param("arrCheckType")Integer[] arrCheckType, @Param("statusList")List<Integer> statusList);

    @Select("<script>" +
            "SELECT * FROM yy_queue.queue " +
            "where id >= #{from} and status in (" +
            " <foreach collection='statusList' separator=',' item='status'>" +
            "  #{status} " +
            " </foreach> )" +
            " limit #{size} " +
            " order by id" +
            "</script>")
    List<QueueDO> getPartialQueueByStatus( @Param("statusList")List<Integer> statusList, @Param("from") Integer from, @Param("size") Integer size);

    @Select("<script>" +
            "SELECT count(1) as total_in_status FROM yy_queue.queue where status in (" +
            " <foreach collection='statusList' separator=',' item='status'>" +
            "  #{status} " +
            " </foreach> );" +
            "</script>")
    Integer statusStatistic(@Param("statusList")List<Integer> statusList);

    @Select("<script>" +
            "SELECT count(1) as total_in_status FROM yy_queue.queue where " +
            " status in ( " +
            " <foreach collection='statusList' separator=',' item='status'>" +
            "  #{status} " +
            " </foreach> ) " +
            " and book_check_type in ( " +
            " <foreach collection='checkTypes' separator=',' item='checkType'>" +
            "  #{checkType} " +
            " </foreach> ) " +
            "</script>")
    Integer checkTypeAndStatusStatistic( @Param("checkTypes")Integer[] checkTypes, @Param("statusList")List<Integer> statusList );

    @Select("<script>" +
            "SELECT room_id, bed_no, count(1) as total_in_status FROM yy_queue.queue where status in (" +
            " <foreach collection='statusList' separator=',' item='status'>" +
            " #{status} " +
            " </foreach> )" +
            " group by room_id, bed_no; "
            +"</script>")
    List<QueueStatisticDO> queueStatistic(@Param("statusList")List<Integer> statusList);

    @Select("<script>" +
            "SELECT status, count(1) as total_in_status FROM yy_queue.queue where " +
            " room_id = #{roomId} and bed_no = #{bedNo} " +
            " group by status " +
            "</script>")
    List<BedQueueStatisticDO> bedQueueStatistic(@Param("roomId")Long roomId, @Param("bedNo")String bedNo);

    @Select("<script>" +
            "SELECT status, count(1) as total_in_status FROM yy_queue.queue where " +
            " room_id = #{roomId} " +
            " group by status " +
            "</script>")
    List<BedQueueStatisticDO> roomQueueStatistic(@Param("roomId")Long roomId);

    @Select("<script>" +
            "SELECT count(1) FROM yy_queue.queue " +
            "where room_id = #{roomId} and bed_no = #{bedNo} and status in (" +
            " <foreach collection='statusList' separator=',' item='status'>" +
            "   #{status} " +
            " </foreach> )" +
            "</script>")
    Integer bedQueueStatisticByStatus(@Param("roomId")Long roomId, @Param("bedNo")String bedNo, @Param("statusList")List<Integer> statusList);

    @Select("<script>" +
            "SELECT * FROM yy_queue.queue " +
            "where room_id = #{roomId} and bed_no = #{bedNo} and status in (" +
            " <foreach collection='statusList' separator=',' item='status'>" +
            "   #{status} " +
            " </foreach> ) " +
            " order by status desc, seq_num " +
            "</script>")
    @Results({
            @Result(property = "patDetails", column = "pat_details", typeHandler=com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler.class)
    })
    List<QueueDO> getBedQueueByStatus(@Param("roomId")Long roomId, @Param("bedNo")String bedNo, @Param("statusList")List<Integer> statusList);

    @Select("SELECT * from yy_queue.queue where room_id = #{roomId} and bed_no = #{bedNo} and status = #{curStatus} order by seq_num, create_time limit 1")
    QueueDO getFirstItemByBedAndStatus(@Param("roomId")Long roomId, @Param("bedNo")String bedNo, @Param("curStatus")Integer curStatus);

    // 某个诊室范围内 [已领用] [已召回-安装] 人员 抢占, 会更新 [工位号]
    // 没有限定检查类型，不要使用时间槽
    @Select("<script> " +
            "select * from yy_queue.queue where room_id = #{roomId} and status in ( " +
            "       <foreach collection='curStatusList' separator=',' item='status'>" +
            "           #{status} " +
            "       </foreach> )" +
            "       order by seq_num, create_time limit 1 " +
            "</script>" )
    QueueDO getFirstItemByRoomAndStatus(@Param("roomId")Long roomId, @Param("curStatusList")List<Integer> curStatusList);

    @Select("<script> " +
            "select * from yy_queue.queue where appoint_id in ( " +
            "       <foreach collection='appointIdList' separator=',' item='appointId'>" +
            "           #{appointId} " +
            "       </foreach> )" +
            "</script>" )
    List<QueueDO> selectBookSeqNumByAppointIdList(@Param("appointIdList") List<Long> appointIdList);

/*
    @Select("select * from yy_queue.queue where room_id = #{roomId} and bed_no = #{bedNo} " +
            " and status = #{curStatus} and pat_id = #{patId} and book_check_type=#{checkType}")
    QueueDO XXX(@Param("roomId")Long roomId, @Param("bedNo")String bedNo,
                                       @Param("patId")String patId, @Param("checkType")Integer checkType,
                                       @Param("curStatus")Integer curStatus);
*/

    @Update("update yy_queue.queue set status = #{newStatus} where pat_id = #{patId} and book_check_type = #{checkType} and status = #{curStatus}; " )
    Integer updatePatientQueueStatus(@Param("patId")String patId, @Param("checkType")Integer checkType, @Param("curStatus")Integer curStatus, @Param("newStatus")Integer newStatus);

    @Update("update yy_queue.queue set status = #{newStatus} where status = #{curStatus} and seq_num = \n" +
            "(select a.min_seq_num from \n" +
            " (select min(seq_num) as min_seq_num from yy_queue.queue where room_id = #{roomId} and bed_no = #{bedNo} and status = #{curStatus}) a )")
    Integer updateBedQueueStatus(@Param("roomId")Long roomId, @Param("bedNo")String bedNo, @Param("curStatus")Integer curStatus, @Param("newStatus")Integer newStatus);

    // 弃用原因：需要先获取，判断逻辑处理后，再更新
    // 某个诊室范围内 [已领用] [已召回-安装] 人员 抢占, 会更新 [工位号]
    // 没有限定检查类型，不要使用时间槽
    @Update("<script> " +
            "update yy_queue.queue set status = #{newStatus}, bed_no = #{bedNo} where id = \n" +
            "  (select a.id from \n" +
            "    (select id from yy_queue.queue where room_id = #{roomId} " +
            "       and status in ( " +
            "           <foreach collection='curStatusList' separator=',' item='status'>" +
            "             #{status} " +
            "           </foreach> )" +
            "       order by seq_num, create_time limit 1 " +
            "    ) a " +
            "  )" +
            "</script>"
    )
    Integer preemptToBeInstalledPatient(@Param("roomId")Long roomId, @Param("bedNo")String bedNo, @Param("curStatusList")List<Integer> curStatusList, @Param("newStatus")Integer newStatus);

    // 整个系统范围内 [排队中]人员 [被工位医生]抢占
    @Update("update yy_queue.queue set status = #{newStatus}, room_id = #{roomId}, room_name = #{roomName}, \n" +
            " bed_no = #{bedNo}, seq_num = #{seqNum} where id = \n" +
            "  (select a.id from \n" +
            "    (select id from yy_queue.queue where status = #{curStatus} and book_check_type= #{checkType} order by jump_flag desc, book_timeslot, create_time limit 1) a)")
    Integer preemptWaitingPatient(@Param("roomId")Long roomId, @Param("roomName")String roomName, @Param("bedNo")String bedNo,
                                  @Param("seqNum")Integer seqNum, @Param("curStatus")Integer curStatus, @Param("newStatus")Integer newStatus,
                                  @Param("checkType")Integer checkType);

    // 整个系统范围内 [排队中]人员 [被工位医生]抢占 根据 多个检查项目
    @Update("<script>" +
            "update yy_queue.queue set status = #{newStatus}, room_id = #{roomId}, room_name = #{roomName}, \n" +
            " bed_no = #{bedNo}, seq_num = #{seqNum} where id = \n" +
            "  (select a.id from \n" +
            "    (select id from yy_queue.queue where status = #{curStatus} " +
            "       and book_check_type in ( " +
            "           <foreach collection='checkTypeArray' separator=',' item='_checkType'>" +
            "             #{_checkType} " +
            "           </foreach> )" +
            "       order by jump_flag desc, book_timeslot, create_time limit 1) a) " +
            "</script>")
    Integer preemptWaitingPatientWithBedCheckTypes(@Param("roomId")Long roomId, @Param("roomName")String roomName, @Param("bedNo")String bedNo,
                                  @Param("seqNum")Integer seqNum, @Param("curStatus")Integer curStatus, @Param("newStatus")Integer newStatus,
                                  @Param("checkTypeArray")Integer[] checkTypeArray);

    @Update("update yy_queue.queue set status = #{newStatus}, seq_num = #{seqNum} " +
            " where id = " +
            "  (select a.id from \n" +
            "    (select id from yy_queue.queue where room_id = #{roomId} and bed_no = #{bedNo} and status = #{curStatus} " +
            "      order by seq_num limit 1" +
            "    ) a" +
            "  )" )
    Integer queueRecalledPatient(@Param("roomId")Long roomId, @Param("roomName")String roomName, @Param("bedNo")String bedNo,
                                 @Param("seqNum")Integer seqNum, @Param("curStatus")Integer curStatus, @Param("newStatus")Integer newStatus);

    // 常规检查 或 领用 的患者召回, 原工位处理
    @Update("update yy_queue.queue set status = #{newStatus}, passed = 1 " +
            " where room_id = #{roomId} and bed_no = #{bedNo} and status = #{curStatus} and pat_id = #{patId} and book_check_type=#{checkType}")
    Integer recallPassedPatient(@Param("roomId")Long roomId, @Param("bedNo")String bedNo,
                                @Param("patId")String patId, @Param("checkType")Integer checkType,
                                @Param("curStatus")Integer curStatus, @Param("newStatus")Integer newStatus);

    // 装机医生 允许抢占 本科室 [安装过号] 的患者
    @Update("update yy_queue.queue set status = #{newStatus}, bed_no = #{bedNo}, passed = 1 " +
            " where room_id = #{roomId} and status = #{curStatus} and pat_id = #{patId} and book_check_type=#{checkType}")
    Integer recallPassedInstallPatient(@Param("roomId")Long roomId, @Param("bedNo")String bedNo,
                                       @Param("patId")String patId, @Param("checkType")Integer checkType,
                                @Param("curStatus")Integer curStatus, @Param("newStatus")Integer newStatus);

    @Update("update yy_queue.queue set jump_flag = #{jumped} " +
            " where status = #{curStatus} and pat_id = #{patId}")
    Integer queueJump(@Param("patId")String patId, @Param("curStatus")Integer curStatus, @Param("jumped")Byte jumped );

    //@Update("TRUNCATE TABLE yy_queue.queue")
    @Delete("delete from yy_queue.queue where TO_DAYS(book_date) != TO_DAYS(NOW())")
    void clearQueue();
}

